package com.example.commen.base;

import static com.example.commen.utile.StatusBarUtil.initbar;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.LogUtils;
import com.example.commen.BuildConfig;
import com.example.commen.R;
import com.example.commen.base.dialoglib.CommonInterface;
import com.example.commen.base.dialoglib.DialogUtils;
import com.example.commen.base.dialoglib.ProgressGifDialog;
import com.example.commen.bean.EventBusEntity;
import com.example.commen.interf.IBaseActivity;
import com.example.commen.resource.CommentContect;
import com.example.commen.view.WaitDialog;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.toast.Toaster;
import com.tencent.bugly.crashreport.CrashReport;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import okhttp3.Call;


public class BaseFragment extends Fragment implements IBaseActivity, TitleBarAction, OnHttpListener<Object> {


    //------------------------------------------------------
    //---------------------------------------------------------------
    /**
     * 标题栏对象
     */
    private TitleBar mTitleBar;
    private WaitDialog.Builder dialog;
    private Parcelable mIntentData;
    private View.OnClickListener titleRightClickListener;
    private View.OnClickListener titleLeftClickListener;
    private View.OnClickListener titleTextViewClickListener;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

    }

    public Parcelable getIntentData() {
        return mIntentData;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initbar(getActivity());
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!BuildConfig.DEBUG){
            try {
                try {
                    if (getArguments() != null) {
                        mIntentData = (Parcelable) getArguments().get(CommentContect.intentKey.Data);
                    }
                } catch (Exception e) {
                }
                initData();
                initListener();
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }else{
            try {
                if (getArguments() != null) {
                    mIntentData = (Parcelable) getArguments().get(CommentContect.intentKey.Data);
                }
            } catch (Exception e) {
            }
            initData();
            initListener();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(EventBusEntity event) {
        LogUtils.i("eventBus:" + "baseFragment" + event.getMsgId());
    }


    public void showProgress(String message) {
        if (getActivity().isDestroyed()) {
            return;
        }
        if (dialog == null || !dialog.isShowing()) {
            dialog = new WaitDialog.Builder(getActivity()).setMessage(message);
//            dialog = new ProgressDialog(getActivity(), message);
            dialog.show();
        }
    }

    public void showProgressOk(String message) {
        if (dialog == null || !dialog.isShowing()) {
            dialog = new WaitDialog.Builder(getActivity()).setMessage(message);
//            dialog = new ProgressDialog(getActivity(), message, false, true);
            dialog.show();
        }
    }

    public void showMessageDialog(String title, String data, CommonInterface.PositiveListener iCell) {
        DialogUtils.getInstance().showCustomTextViewDialog(getActivity(), title, data, false,
                getString(R.string.yes), iCell);
    }

    public void dismissProgress() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    public void ShowToast(String string) {
        Toaster.cancel();
        Toaster.show(string);
        LogUtils.i("Toaster:"+string);
    }

    private ProgressGifDialog gifDialog;

    public void showGifProgress(String message) {
        if (gifDialog == null || !gifDialog.isShowing()) {
            tim = System.currentTimeMillis();
            gifDialog = new ProgressGifDialog(getContext(), message);
            gifDialog.show();
        }
    }

    public boolean isShowGuaT() {
        if (gifDialog == null) {
            return gifDialog.isShowing();
        }
        return false;
    }

    private long tim = 0;


    public void goToActivity(Activity context, Class toActivity) {
        Intent intent = new Intent(context, toActivity);
        startActivity(intent);
        context.overridePendingTransition(0, 0);
    }

    public void goToActivityNoAnim(Activity context, Class toActivity) {
        Intent intent = new Intent(context, toActivity);
        startActivity(intent);
        context.overridePendingTransition(0, 0);
    }

    public void goToActivity(Context context, Class toActivity, String data) {
        Intent intent = new Intent(context, toActivity);
        intent.putExtra(CommentContect.intentKey.Data, data);
        startActivity(intent);
        requireActivity().overridePendingTransition(0, 0);
    }

    public void goToActivity(Context context, Class toActivity, Object data) {
        Intent intent = new Intent(context, toActivity);
        intent.putExtra(CommentContect.intentKey.Data, (Parcelable) data);
        startActivity(intent);
        requireActivity().overridePendingTransition(0, 0);
    }

    public void goToActivityResult(Context context, Class toActivity, Parcelable data, ActivityResultLauncher<Intent> callback) {
        Intent intent = new Intent(context, toActivity);
        intent.putExtra(CommentContect.intentKey.Data, data);
        callback.launch(intent);
        requireActivity().overridePendingTransition(0, 0);
    }


    @Override
    public void initListener() {

    }

    @Override
    public void initData() {

    }

    /**
     * 和 setContentView 对应的方法
     */
    public ViewGroup getContentView() {
        return getActivity().findViewById(Window.ID_ANDROID_CONTENT);
    }

    /**
     * 设置标题栏的标题
     */
    @Override
    public void setTitle(@StringRes int id) {
        setTitle(getString(id));
    }


    /**
     * 设置标题栏的标题
     */
    @Override
    public void setTitle(CharSequence title) {
        getActivity().setTitle(title);
        if (getTitleBar() != null) {
            getTitleBar().setTitle(title);
        }
    }


    @Override
    public void onLeftClick(View view) {
        getActivity().onBackPressed();
    }

    @Override
    @Nullable
    public TitleBar getTitleBar() {
//        if (mTitleBar == null) {
        mTitleBar = obtainTitleBar(getlayoutView());
        mTitleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View view) {
                if (titleLeftClickListener != null) {
                    titleLeftClickListener.onClick(view);
                } else {
                    getActivity().onBackPressed();
                }

            }

            @Override
            public void onTitleClick(View view) {
                if (titleTextViewClickListener != null)
                    titleTextViewClickListener.onClick(view);
            }

            @Override
            public void onRightClick(View view) {
                if (titleRightClickListener != null) {
                    titleRightClickListener.onClick(view);
                }
            }
        });
//        }
        return mTitleBar;
    }

    public TitleBar setTitleRightClickListener(int imageViewId, View.OnClickListener onClickListener) {
        titleRightClickListener = onClickListener;
        if (imageViewId != -1 && mTitleBar != null) {
            mTitleBar.setRightIcon(imageViewId);
        }
        return mTitleBar;
    }

    public TitleBar setTitleLeftClickListener(View.OnClickListener onClickListener) {
        titleLeftClickListener = onClickListener;
        return mTitleBar;
    }

    public TitleBar setTitleTextViewClickListener(View.OnClickListener onClickListener) {
        titleTextViewClickListener = onClickListener;
        return mTitleBar;
    }

    private ViewGroup getlayoutView() {
        return (ViewGroup) getView();
    }


    private ArrayList<Long> progressDialogMap = new ArrayList<>();

    @Override
    public void onStart(Call call) {
        if (progressDialogMap.isEmpty()) {
            showProgress("加载中...");
        }
        progressDialogMap.add(System.currentTimeMillis());
    }

    @Override
    public void onSucceed(Object result) {

    }

    @Override
    public void onFail(Exception e) {
        CrashReport.postCatchedException(e);
    }

    @Override
    public void onEnd(Call call) {
        if (!progressDialogMap.isEmpty()){
            progressDialogMap.remove(0);
        }
        if (progressDialogMap.isEmpty()) {
            dismissProgress();
        }
    }
}
